package com.ma4567.remotecontroller.FileRequest;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ma4567.remotecontroller.MysqlHelper.TableLogManager;
import com.ma4567.remotecontroller.MysqlHelper.TableRequestLog;
import com.ma4567.remotecontroller.RemoteControllerApplication;
import com.ma4567.remotecontroller.UserManager.UserManager;
import com.ma4567.remotecontroller.ffmpegManager.ffmpegController;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.sql.SQLException;

class FileDownloadRespone
{
    public int Status;

    public FileDownloadRespone(int status)
    {
        this.Status = status;//0 正常 1 cookie错误 2 文件不存在 3 没有下载文件权限
    }
}

@CrossOrigin
@RestController
public class FileDownloadRequest {
    @RequestMapping(value = "/api/downloadFile", method = RequestMethod.GET)
    public String FielDownload(HttpServletResponse response,
                               HttpServletRequest request,
                               @RequestParam("cookie") String Cookie,
                               @RequestParam("path") String path) throws SQLException {
        ffmpegController.StopStream();

        TableRequestLog.AddLog("Download file: " + path, Cookie, request.getRemoteAddr());

        if(!RemoteControllerApplication.userManager.JudgeCookie(Cookie)){//鉴权
            return JSONObject.toJSONString(new FileDownloadRespone(1), SerializerFeature.PrettyFormat);
        }
        else{
            if(!RemoteControllerApplication.userManager.GetUserSingleItemPermission(Cookie, "DownloadFile")){
                return JSONObject.toJSONString(new FileDownloadRespone(3), SerializerFeature.PrettyFormat);
            }

            File file = new File(path);
            if(file.exists() && file.isFile()){
                response.reset();
                response.setCharacterEncoding("UTF-8");

                try {
                    response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
                    response.setContentType("application/octet-stream");

                    try (InputStream is = new BufferedInputStream(Files.newInputStream(file.toPath()))) {

                        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());

                        byte[] buffer = new byte[1024];
                        int len;

                        while ((len = is.read(buffer)) > 0) {
                            outputStream.write(buffer, 0, len);
                        }

                        outputStream.close();
                    }
                }catch (IOException e) {
                    throw new RuntimeException(e);
                }

                TableLogManager.AddLog("Download file: " + path, Cookie);
                return JSONObject.toJSONString(new FileDownloadRespone(0), SerializerFeature.PrettyFormat);
            }
            else{
                return JSONObject.toJSONString(new FileDownloadRespone(2), SerializerFeature.PrettyFormat);
            }
        }
    }
}
